<template>
  <div>
    <div class="head-div" ref="head-div">
      <ul style="display: flex; margin: 0 10px;flex: 1">
        <li><i :class="['iconfont', contentFlag ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"
               style="cursor: pointer" @click="tiggerFun"></i></li>
        <li><p>{{formatDatetime(new Date())}}</p></li>
        <li><p>{{localSoruceData.Name}}</p></li>
<!--        <li title="新增泳道"><i class="el-icon-plus" style="cursor: pointer" @click="addChild"></i></li>-->
        <li title="删除泳道"><i class="el-icon-minus" style="cursor: pointer" @click="delChild"></i></li>
      </ul>
      <ul style="display: flex; margin: 0 10px;">
        <li v-if="ToPlanCheck()"><el-button @click="ToPlan">一键转计划</el-button></li>
        <li v-else><el-button @click="GoToTask">跳转任务</el-button></li>
      </ul>
    </div>
    <div class="content-div all_div_transition" ref="content-div" @contextmenu="openContextMenu">
      <div v-if="contentFlag">
        <trag-item v-for="(item, index) in localSoruceData.child" :scrollFun="scrollFun" ref="item"
                   :itemPosition="itemPosition" @contextmenu.native.stop="(e) => openContextMenu(e, index, item)"
                   :dragData.sync="item" :key="index" class="item" :type="item.type" @dblclick.native="tragDbClick(item)"></trag-item>
        <div class="vdr-stick vdr-stick-bm" v-if="localType('bm')" v-trag-tl="{type: 'bm', parentNodeFun: parentNodeFun, callBmFun: callBmFun}"></div>
        <div v-show="contextMenuVisible" style="z-index: 10000000000">
          <ul :style="{left: left+'px', top: top+'px'}" class="contextmenu">
            <li v-if="deleteIndex === -1" @click="addNode()"><el-button type="text" size="mini">新增节点</el-button></li>
            <li v-else @click="deleteNode"><el-button type="text" size="mini">删除</el-button></li>
          </ul>
        </div>
      </div>
    </div>
    <drag-dialog :visible.sync="dragEditVisible" :title="dragEditTitle" :form="dragEditForm"></drag-dialog>
    <plan-dialog :visible.sync="planEditVisible" :formData="planEditForm">></plan-dialog>
  </div>
</template>

<script>
import { dragTl } from "@/page/ProjectManage/modules/task/demandTrag/drag_canvers";
import tragItem from "../task/demandTrag/tragItem";
import dragDialog from "../task/demandTrag/dragDialog";
import * as format from '@/filters/index'
import projectNeedApi from "@/api/organizationApi/projectNeedApi";
import PlanDialog from "./Plan/PlanDialog";

export default {
  name: 'needListItem',
  inject: {
    initData: {
      default: null
    }
  },
  components: {
    tragItem,
    dragDialog,
    PlanDialog
  },
  directives: {
    tragTl: dragTl
  },
  props: {
    itemPosition: {
      type: Object,
      default: () => {
        return null
      }
    },
    moveXYFun: {
      type: Function,
      default: () => {
        return null
      }
    },
    soruceData: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  computed: {
    localSoruceData: {
      get () {
        return this.soruceData
      },
      set (val) {
        this.$emit('update:soruceData', val)
      }
    }
  },
  data () {
    return {
      planEditVisible: false,
      planEditForm: {},
      isClick: false,
      clickData: null,
      dragEditForm: {},
      throttleLoading: false,
      preHeight: undefined,
      dragEditVisible: false,
      dragEditTitle: '修改',
      contentFlag: true,
      headHeight: 0,
      contentHeight: 0,
      contextMenuVisible: false,
      left: 0,
      top: 0,
      deleteIndex: -1,
      item: {
        id: 1,
        x: 0,
        y: 0,
        localHeight: 100,
        localWidth: 100
      },
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initDataFun()
    })
  },
  methods: {
    ToPlanCheck () {
      if (!this.localSoruceData.Planid) {
        return true
      } else {
        return this.localSoruceData.Planid === '0'
      }

    },
    // 选中
    // isClickFun (isclick, data) {
    //   this.isClick = isclick
    //   this.clickData = data
    // },
    // 跳转到任务
    GoToTask () {
      this.$router.push(`/view/project/task/${this.localSoruceData.Planid}`)
    },
    // 一键转计划
    ToPlan () {
      // if (this.isClick) {
      let a = {
        id: this.localSoruceData.id
      }
      this.planEditForm = a
      this.planEditVisible = true
    },
    formatDatetime (date, formatStr='yyyy-MM-dd') {
      return format.formatDatetime(new Date(), formatStr)
    },
    openContextMenu (e, index, item) {
      if (e.target.className.indexOf('content-div') >= 0 || e.target.className.indexOf('item') >= 0) {
        e.preventDefault() //防止默认菜单弹出
        if (e.target.className.indexOf('item') >= 0) {
          this.left = e.offsetX + Number((item.x||'').toString().replace('px', ''))
          this.top = e.offsetY + Number((item.y||'').toString().replace('px', ''))
          this.deleteIndex = index
        } else {
          this.deleteIndex = -1
          this.left = e.offsetX
          this.top = e.offsetY
          this.item.x = this.left
          this.item.y = e.offsetY
        }
        this.contextMenuVisible = true
        this.$nextTick(() => {
          document.addEventListener('mouseup', this.addClick)
        })
      }
    },
    // 监听点击
    addClick (e) {
      this.contextMenuVisible = false
      document.removeEventListener('mouseup', this.addClick)
    },
    initDataFun () {
      this.headHeight = this.$refs['head-div'].clientHeight
      this.contentHeight = this.$refs['content-div'].clientHeight
      this.localSoruceData.child.forEach(it => {
        it.headHeight = this.headHeight
        it.contentHeight = this.contentHeight
      })
      this.localSoruceData.headHeight = this.headHeight
      this.localSoruceData.contentHeight = this.contentHeight
    },
    callBmFun (h) {
      let a = this.localSoruceData.child.map(it => {
        let y = (it.y||0).toString().replace('px', '')
        let h = (it.localHeight||0).toString().replace('px', '')
        return Number(y) + Number(h)
      })
      a = Math.max(...a)
      let tb = this.localSoruceData.child[0].paddingtb
      if (h <= (a + tb)) h = a + tb
      this.localSoruceData.child.forEach(it => {
        it.contentHeight = h
      })
      return h
    },
    //
    parentNodeFun (el) {
      return el.parentNode.parentNode
    },
    // 新增节点
    addNode (e) {
      this.dragEditTitle = '新增'
      this.dragEditVisible = true
      let a = {
        Xcoordinate: this.item.x,
        Ycoordinate: this.item.y,
        High: this.item.localHeight,
        Width: this.item.localWidth,
        Crosswise: this.localSoruceData.id
      }
      this.dragEditForm = a
      // console.log(this.item)
      // this.contextMenuVisible = false
      // this.localSoruceData.child.push(JSON.parse(JSON.stringify(this.item)))
    },
    // 删除节点
    deleteNode (e) {
      let item = this.localSoruceData.child
      if (this.deleteIndex >= 0) {
        this.$alert('确认是否删除本条数据', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            if (action === 'confirm') {
              projectNeedApi.deleteById(item[this.deleteIndex]).then(res => {
                if (res) this.$message({type: res.code === 1 ? 'success' : 'error', message: res.message})
                if (res.code === 1) {
                  this.localSoruceData.child.splice(this.deleteIndex, 1)
                }
              })
            }
          }
        })
      }
    },
    // 删除泳道
    delChild () {
      if (this.localSoruceData.child.length > 0) {
        this.warning("该泳道有数据暂不可删除")
      } else {
        this.$emit('delLane', this.itemPosition)
      }
    },
    // 添加
    addChild () {

    },
    tiggerFun () {
      if (this.throttleLoading === false) {
        if (this.$refs['content-div'].style.height === '0px') {
          this.throttleLoading = true
          setTimeout(() => {
            this.contentFlag = !this.contentFlag
            this.throttleLoading = false
          }, 300)
          this.$refs['content-div'].style.height = (this.preHeight || '').toString().replace('px', '') + 'px'
        } else {
          this.throttleLoading = true
          this.preHeight = this.$refs['content-div'].clientHeight
          this.$refs['content-div'].style.height = 0
          this.$nextTick(() => {
            this.throttleLoading = false
            this.contentFlag = !this.contentFlag
          })
        }
      }
    },
    scrollFun(x, y) {
      this.initDataFun()
      let ih = this.$refs.item[0].$el.clientHeight
      // let w = this.$refs['content-div'].clientWidth
      if (this.moveXYFun) {
        let xy = this.moveXYFun(x, y, this.headHeight, this.contentHeight, ih)
        x = xy.x
        y = xy.y
      }
      return {
        x, y
      }
    },
    // 弹窗双击
    tragDbClick (item) {
      if (!item.type) {
        this.dragEditTitle = '编辑栏'
        this.dragEditVisible = true
        this.dragEditForm = JSON.parse(JSON.stringify(item))
      }
    },
    localType (type) {
      if (this.type) {
        if (this.type === 'vertical') {
          return type === 'tm' || type === 'bm';
        } else if (this.type === 'horizontal') {
          return type === 'mr' || type === 'ml';
        }
        return true
      }
      return true
    }
  }
}
</script>

<style scoped lang="scss">
.all_div_transition {
  //transition: height .5s;
}
.contextmenu {
  width: 100px;
  margin: 0;
  border: 1px solid #ccc;
  background: #fff;
  z-index: 3000;
  position: absolute;
  list-style-type: none;
  padding: 5px 0;
  border-radius: 4px;
  font-size: 14px;
  color: #333;
  box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.2);
}
.contextmenu li {
  margin: 0;
  padding: 0px 22px;

}
.contextmenu li:hover {
  background: #f2f2f2;
  cursor: pointer;
}
.contextmenu li button{
  color: #2c3e50;
}

.head-div {
  height: 40px;
  width: 100%;
  border: 1px solid #cccccc;
  display: flex;
  align-items: center;
  li {
    list-style: none;
  }
  li+li{
    margin-left: 10px;
  }
}
.content-div {
  position: relative;
  height: 400px;
  border: 1px solid #cccccc;
  width: 100%;
}
.vdr-stick {
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  font-size: 1px;
  background: #fff;
  border: 1px solid #6c6c6c;
  -webkit-box-shadow: 0 0 2px #bbb;
  box-shadow: 0 0 2px #bbb;
  position: absolute;
  width: 8px;
  height: 8px;
  right: calc(50% - 4px);
  bottom: 10px;
}
/*下*/
.vdr-stick-bm:hover {
  cursor: ns-resize;
}
</style>
